#!/usr/bin/env python

from dotext import dotext
from tobconf import logsize

import cPickle
import sys
import os
import time


#loglines and logtimes ought to be combined in a compound type.

global logidx
global logtimes
global loglines

def init_logging():
  global logidx
  global logtimes
  global loglines
  logidx = 0
  logtimes = []
  loglines = []
  # Pregen our round-robin log buffer.
  for t in range(0, logsize):
    loglines.append(0)
    logtimes.append(0)
  

# Where this was pulled from, there was a 'self' argument, but it wasn't used.
# Where this was pulled from, there was a 'slog' argument, but it was never
# passed a value, so it was always used as default. The function has been
# simplified to reflect this as its only observed usage.
def log(txt):
  global logidx
  global loglines
  global logtimes
  try:
    test = logidx
  except:
    init_logging()
  
  dotext ("`9Log "+str(logidx)+"/"+str(logsize)+" ["+str(time.localtime()[3]).zfill(2)+":"+str(time.localtime()[4]).zfill(2)+"."+str(time.localtime()[5]).zfill(2)+"]: "+txt)
  loglines[logidx] = txt
  loglines[logidx] = int(time.time())
  logidx += 1
  # I'd make it logidx = logsize, but someone might set logsize to 0.
  if logidx >= logsize:
    logidx = 0

# gzipin(fn) -- gunzips a cPickle
def gzipin(fn): 
  sys.stdout.flush()
  p = os.popen("gunzip -c '"+fn+"'")
  sys.stdout.flush()
  lines = "".join(p.readlines())
  p.close()
  sys.stdout.flush()
  return cPickle.loads(lines)

def gzipout(fn, gherkin):
  gzt = ""
  gzt = cPickle.dumps(gherkin)
  gherkin = ""
  (po, pi) = os.popen2("gzip -9 -c > '"+fn+"'")
  po.write(gzt)
  po.close()
  pi.close()
  n = len(gzt)
  return n

# Based on several similar sections of code found in tobmalf's main func
# Note that whatever it's opening, it will attempt to run len() on it!
def loadobj(filename, default, description):
  dotext("`2loading " + description + "...", sameline=1)
  try:
    retpickle = gzipin(filename)
    dotext(str(len(retpickle)) + " loaded.", sameline=0)
  except:
    retpickle = default
    dotext("`@failed. None loaded.", sameline=0)
  return retpickle

